package cn.cangfei.massage.controller;

import cn.cangfei.massage.common.api.CommonPage;
import cn.cangfei.massage.common.api.CommonResult;
import cn.cangfei.massage.dto.*;
import cn.cangfei.massage.dto.param.VisitAppointmentParam;
import cn.cangfei.massage.dto.update.VisitAppointmentWithDoctor;
import cn.cangfei.massage.entity.VisitAppointment;
import cn.cangfei.massage.service.IMassageDoctorService;
import cn.cangfei.massage.service.IPowerAccountService;
import cn.cangfei.massage.service.IUserMedicalCardService;
import cn.cangfei.massage.service.IVisitAppointmentService;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.Date;

/**
 * @author Lemon  2313812755@qq.com
 * @date 2023/3/19
 */

@Api(value = "出诊模块", tags = "出诊预约接口")
@RestController
@CrossOrigin
@RequestMapping("/visit")
public class VisitAppointmentController {

    @Resource
    private IPowerAccountService accountService;

    @Resource
    private IVisitAppointmentService appointmentService;


    @Resource
    private IUserMedicalCardService userMedicalCardService;

    @Resource
    private IMassageDoctorService massageDoctorService;

    @ApiOperation(value = "添加预约信息", notes = "传入 预约参数对象（出诊编号、就诊卡号、账号编号）")
    @RequestMapping(value = "/appointment", method = RequestMethod.POST)
    public CommonResult insertAppointment(Principal principal, @RequestBody VisitAppointmentParam param, @RequestParam("count") Integer count, @RequestParam("hospId") Long hospId) {


        // 这个name是account里面的name 也就是openId
        String name = principal.getName();

        boolean insert = appointmentService.insert(name, param, count, hospId);
        if (insert) {
            return CommonResult.success();
        }

        return CommonResult.failed();
    }

    @ApiOperation("定时扫描看是否重复预约")
    @RequestMapping(value = "/appointment/scan", method = RequestMethod.GET)
    public CommonResult scanAppointment() {

        appointmentService.deleteRepeat();


        return CommonResult.success();
    }

    @ApiOperation(value = "判断是否已预约", notes = "传入 出诊编号、就诊卡号")
    @RequestMapping(value = "/appointment/check", method = RequestMethod.GET)
    public CommonResult checkAppointment(@RequestParam Long cardId, @RequestParam Long planId) {

        if (userMedicalCardService.countCardId(cardId)) {
            return CommonResult.validateFailed("不存在，该就产品或该产品被下架！");
        }


        return CommonResult.success(appointmentService.count(cardId, planId));
    }


    @ApiOperation(value = "批量删除预约记录", notes = "传入 删除的类型")
    @RequestMapping(value = "/appointment/delete/visit", method = RequestMethod.DELETE)
    public CommonResult deleteVisitAppointment(@RequestParam("type") Integer type) {

        boolean result = appointmentService.deleteVisitAppointment(type);

        if (result) {
            return CommonResult.success();

        }
        return CommonResult.failed();
    }

    @ApiOperation(value = "修改预约状态：取消", notes = "传入 预约编号")
    @RequestMapping(value = "/appointment/cancel/{id}", method = RequestMethod.PUT)
    public CommonResult cancelAppointment(@PathVariable Long id) {

        updateAppointmentStatus(id, AppointmentEnum.CANCEL.getStatus());

        // 下面就是去给这个师傅发送消息
        appointmentService.cancelAppointment(id);

        return CommonResult.success();
    }

    @ApiOperation(value = "修改预约状态：迟到", notes = "传入 预约编号")
    @RequestMapping(value = "/appointment/miss/{id}", method = RequestMethod.PUT)
    public CommonResult missAppointment(@PathVariable Long id) {

        return updateAppointmentStatus(id, AppointmentEnum.MISSING.getStatus());
    }

    @ApiOperation(value = "修改预约状态：完成", notes = "传入 预约编号")
    @RequestMapping(value = "/appointment/finish/{id}", method = RequestMethod.PUT)
    public CommonResult finishAppointment(@PathVariable Long id) {

        return updateAppointmentStatus(id, AppointmentEnum.FINISH.getStatus());
    }

    @ApiOperation(value = "提前90分钟提醒")
    @RequestMapping(value = "/appointment/tixing", method = RequestMethod.GET)
    public CommonResult tixing() {

        appointmentService.tixing();
        return CommonResult.success();
    }


    @ApiOperation(value = "查找挂号记录", notes = "传入用户编号、挂号状态")
    @RequestMapping(value = "/appointment/search", method = RequestMethod.GET)
    public CommonResult<CommonPage<VisitAppointment>> searchAppointment(@RequestParam(required = false) String userName, @RequestParam(required = false) Integer status, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {

        return CommonResult.success(CommonPage.restPage(appointmentService.list(userName, status, pageNum, pageSize)));
    }

    @ApiOperation(value = "获取这个师傅的所有预约记录（并且会自动修改用户时候迟到）", notes = "传入师傅id，页码")
    @RequestMapping(value = "/appointment/doctor/all", method = RequestMethod.GET)
    public CommonResult<IPage<VisitAppointmentWithDoctor>> listAllAppointmentWithDoctor(@RequestParam(required = false) Long doctorId, @RequestParam(required = false) String day, @RequestParam(required = false) Integer status, @RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {

        IPage<VisitAppointmentWithDoctor> page = appointmentService.listAllAppointmentWithDoctor(doctorId, day, status, pageNum, pageSize);

        return CommonResult.success(page);
    }

    @ApiOperation(value = "获取所有挂号记录(小程序端获取个人的)", notes = "传入页码")
    @RequestMapping(value = "/appointment/all", method = RequestMethod.GET)
    public CommonResult<CommonPage<VisitAppointmentWithQueueDTO>> listAllAppointment(Principal principal, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {


        String name = principal.getName();
        return CommonResult.success(CommonPage.restPage(appointmentService.listAllAppointment(name, pageNum, pageSize)));
    }

    @ApiOperation(value = "获取所有挂号记录(后台管理的，一旦查询就会判断)", notes = "传入页码")
    @RequestMapping(value = "/appointment/account/all", method = RequestMethod.GET)
    public CommonResult<CommonPage<VisitAppointmentWithQueueDTO>> listAllAccountAppointment(@RequestParam(required = false) String userName, @RequestParam(required = false) Integer status, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {


        return CommonResult.success(CommonPage.restPage(appointmentService.listAllAccountAppointment(userName, status, pageNum, pageSize)));
    }

    @ApiOperation(value = "获取失信记录详情", notes = "传入预约编号")
    @RequestMapping(value = "/appointment/miss/details", method = RequestMethod.GET)
    public CommonResult<VisitAppointmentWithQueueDTO> listAllAppointment(@RequestParam Long appointmentId) {

        if (!appointmentService.count(appointmentId)) {
            return CommonResult.validateFailed("不存在，该预约编号！");
        }

        return CommonResult.success(appointmentService.getAppointmentDetails(appointmentId));
    }

    @ApiOperation(value = "获取就诊记录列表", notes = "传入页面")
    @RequestMapping(value = "/appointment/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<VisitAppointmentDTO>> listAppointment(Principal principal, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {


        // 得到openId
        String name = principal.getName();
        return CommonResult.success(CommonPage.restPage(appointmentService.listNormalAppointment(name, pageNum, pageSize)));
    }

    @ApiOperation(value = "查看就诊记录详情", notes = "传入就诊卡编号")
    @RequestMapping(value = "/appointment/details", method = RequestMethod.GET)
    public CommonResult<VisitAppointmentWithCaseDTO> getAppointmentDetails(@RequestParam Long appointmentId) {

        if (!appointmentService.count(appointmentId)) {
            return CommonResult.validateFailed("不存在，该预约编号！");
        }

        return CommonResult.success(appointmentService.getVisitAppointmentWithCaseDTO(appointmentId));
    }

    @ApiOperation(value = "查看当天排队信息", notes = "传入就诊卡编号、账号编号")
    @RequestMapping(value = "/appointment/today", method = RequestMethod.GET)
    public CommonResult<CommonPage<VisitAppointmentQueueDTO>> getTodayAppointment(@RequestParam Long cardId, @RequestParam Long accountId, @RequestParam String date) {

        if (userMedicalCardService.countCardId(cardId)) {
            return CommonResult.validateFailed("不存在，该就诊卡编号！");
        }

        if (!accountService.count(accountId)) {
            return CommonResult.validateFailed("不存在，该账号编号！");
        }

        return CommonResult.success(CommonPage.restPage(appointmentService.listTodayQueue(DateUtil.parseDate(date), cardId, accountId)));
    }

    @ApiOperation(value = "查看用户预约情况", notes = "传入师傅编号、日期、时间段（上午：1、下午：2）")
    @RequestMapping(value = "/appointment/user", method = RequestMethod.GET)
    public CommonResult<CommonPage<VisitUserInfoDTO>> listVisitUserInfo(@RequestParam Long doctorId, @RequestParam String date, @RequestParam Integer time, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {

        if (!massageDoctorService.count(doctorId)) {
            return CommonResult.validateFailed("不存在，该师傅编号");
        }

        Date day = DateUtil.parse(date);

        return CommonResult.success(CommonPage.restPage(appointmentService.listVisitUserInfo(doctorId, time, day, pageNum, pageSize)));
    }

    @ApiOperation(value = "查看获取预约诊室名称", notes = "传入师傅编号、日期、时间段（上午：1、下午：2）")
    @RequestMapping(value = "/appointment/clinic", method = RequestMethod.GET)
    public CommonResult getClinicName(@RequestParam Long doctorId, @RequestParam String date, @RequestParam Integer time) {

        if (!massageDoctorService.count(doctorId)) {
            return CommonResult.validateFailed("不存在，该师傅编号");
        }

        Date day = DateUtil.parse(date);

        return CommonResult.success(appointmentService.getClinicName(doctorId, time, day));
    }

    /**
     * 更新预订状态
     *
     * @param id     预订编号
     * @param status 状态：1 失约，2 取消， 3 完成
     * @return 更新情况
     */

    @ApiOperation(value = "更新预订状态", notes = "传入 id 以及状态")
    @RequestMapping(value = "updateStatus", method = RequestMethod.POST)
    private CommonResult updateAppointmentStatus(@RequestParam("id") Long id, @RequestParam("status") Integer status) {
        if (!appointmentService.count(id)) {
            return CommonResult.validateFailed("不存在，该预约编号！");
        }

        if (appointmentService.update(id, status)) {
            return CommonResult.success();
        }

        return CommonResult.failed();
    }

    @ApiOperation(value = "定时更新", notes = "传入 轮播图信息参数（轮播图编号）")
    @RequestMapping(value = "/updateStatusByLunXun", method = RequestMethod.GET)
    public CommonResult updateStatusByLunXun() {

        appointmentService.updateAppointmentStatusForCancel();
        appointmentService.updateAppointmentStatusForCancel();

        return CommonResult.success();


    }
}
